package cola.project.hellojavaee.servlet;

import cola.project.hellojavaee.entity.User;
import cola.project.hellojavaee.mapper.UserMapper;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.util.Map;

@WebServlet(name = "loginServlet" ,value = "/login-servlet")
public class LoginServlet extends HttpServlet {


    SqlSessionFactory factory;
    @SneakyThrows
    @Override
    public void init() throws ServletException {
        factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis-config.xml"));
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        resp.getWriter().write("我是 loginServlet 的 doGet 响应的内容");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        resp.setContentType("text/html;charset=UTF-8");
        Map<String, String[]> map = req.getParameterMap();

        if (map.containsKey("username") && map.containsKey("password")) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");
            try {
                SqlSession sqlSession = factory.openSession(true);
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                User user = mapper.getUser(username, password);
                if (user != null){
                    resp.getWriter().write("登录成功");

/*                    // 通过 ServletContext 携带参数
                    ServletContext servletContext = getServletContext();
                    servletContext.setAttribute("cola","Login-POST)重定向之前的数据");

                    // 重定向至 time-servlet
                    resp.sendRedirect("time-servlet");*/

                }else {
                    resp.getWriter().write("登录失败");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            System.out.println("form: "+username+password);
        }else {
            resp.getWriter().write("参数不完整");
        }
    }

    @Override
    public void destroy() {
        super.destroy();
    }

}
